Ajax ASP.net C#(cSharp) Javascript 

How to upload file to ftp using C#(C-Sharp) – aspx,ashx and ajax

In this article, we are going to explain how to upload the file to FTP using C# Generic handler(.ashx), HTML and Ajax.

Please follow the steps below

  • In visual studio create a solution with empty web app with aspx project solution.
    Create a file called index.aspx by adding a new item to the solution, in aspx page add the below code
  • Add jquery plugin to <head> tag section
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
jquery google CDN link
  • Add HTML form fields to upload a file
 <div>
        <input type="file" id="fileupload"/>

        <button type="button" id="submithere">upload</button>
    </div>
HTML for File Upload
  • At bottom add the ajax file upload ajax script.
<script>
        $(document).ready(function () {
            $("#submithere").click(function () {

            var formData = new FormData();// it creats form object
            formData.append('file', $('#fileupload')[0].files[0]); //it reads file from from HTML form
                        
                $.ajax({
                    type: 'post',//method i which we need to upload the file
                    url: 'fileupload.ashx',//the is the .ashx fileuload handler
                    data: formData,//file data
                    success: function (status) {
                        alert(status);//status here is returned with the file url where it is stored with path from this save the file name to DB.
                    },
                    processData: false,
                    contentType: false,
                    error: function () {
                        overlayProgress.remove();
                        console.error("Whoops something went wrong!");
                    }
                });
            });
        });
    </script>
  • After this create a File upload handler using generic handler(.ashx) by adding new item
  • Here inside Process request add the below-written code.
public void ProcessRequest(HttpContext context)
        {
            try
            {
                string halfpath = "Uploads/";//path for ftpupload
                string str_image = "";
                long ticks = DateTime.Now.Ticks; //using date creating unique file.
                foreach (string s in context.Request.Files)//here we can upload single/multiple files at a time. 
                {
                    HttpPostedFile file = context.Request.Files[s];
                    string fileName = file.FileName;
                    string fileExtension = file.ContentType;//get file extension

                    if (!string.IsNullOrEmpty(fileName))
                    {
                        fileExtension = Path.GetExtension(fileName);
                        str_image = "file" + ticks.ToString() + fileExtension;
                        string localpath = HttpContext.Current.Server.MapPath("~/Uploads/") + str_image;// gets full path where the file to be uploaded.
                        file.SaveAs(localpath);// this saves the file in local application directory
                        halfpath += str_image;//here it create the full file path where file should be uploaded in FTP.
                        string res = UploadFile(localpath, halfpath);// this calls the FTP UploadFile function to upload the file.
                    }
                }
                context.Response.Write(halfpath);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
local file upload

You might think why this file is uploading to the application(solution) local directory and then using that path it is being uploaded to FTP?, Because using Ajax – javascript, browser cannot read the physical/original path of the initial file upload PC  path because of security reason browser do not allow javascript to read, so when we select the file from PC browser create fake-path of file and upload it to local application directory, from there it creates application local path and sends to FTP for uploading File.

  • Then add FTP File upload below this process request function in .ashx. In FTP username and password section, please use your credentials.
public static string UploadFile(string path, string upload_path)
        {
           
            string ip = "192.168.1.1";// please enter your ip/ftp url here
            string username = "username";//Enter your FTP user name
            string password = "password";//Enter your FTP password name

            string fullpath = "ftp://" + ip + "/" + upload_path; //with ip/url create a ftp path where you will upload

            FileInfo fileInf = new FileInfo(path);

            FtpWebRequest reqFTP;
            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(fullpath);
            // Provide the WebPermission Credentials
            reqFTP.Credentials = new NetworkCredential(username, password);
            reqFTP.Proxy = null; //Set Proxy to be null
            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;
            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            // reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
            // Specify the data transfer type.
            reqFTP.UseBinary = true;
            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;
            //SSL
            reqFTP.EnableSsl = false;
            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Stream to which the file to be upload is written
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                FileStream fs = fileInf.OpenRead();
                try
                {
                    do
                    {
                        contentLen = fs.Read(buff, 0, buffLength);
                        strm.Write(buff, 0, contentLen);
                    } while (contentLen != 0);
                    fs.Close();
                    strm.Close();
                }
                catch (WebException ex)
                {
                    String status = ((FtpWebResponse)ex.Response).StatusDescription;
                    return ex.ToString();
                }
            }
            catch (WebException ex)
            {
                String status = ((FtpWebResponse)ex.Response).StatusDescription;
                return ex.ToString();
            }
            //here it will delete the file from local application temp location after uploading to ftp server.
            if ((System.IO.File.Exists(path)))
            {
                System.IO.File.Delete(path);
            }
            return "1";
        }

FTP c# File Upload

For full project click on below button to download full demo solution.

Also Read:  Property 'updated' in type 'CdsIcon' is not assignable to the same property in base type 'LitElement'

I know this solution may not be the best, but it works for me, so if anyone knows the even easier solution please leave a link in the comment section below.

 

Related posts